<template>
  <div class="upupload">
    <el-upload action="/" list-type="picture-card" :before-upload="beforeAvatarUpload">
      <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
import { uploadPicture } from "@/api/article/group"
export default {
  data() {
    return {
      dialogImageUrl: '',
      fileName: "",
    }
  },
  mounted() {

  },
  methods: {
    beforeAvatarUpload(file) {
      console.log(file);
      const type = ["image/png", "image/jpg", "image/gif", "image/jpeg"];
      const isJPG = type.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片支持jpg、png、gif格式!");
      } else if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      } else {
        const formData = new FormData();
        formData.append("file", file);
        uploadPicture(formData).then((res) => {
          if (res.code === 200) {
            let url = res.data.url;
            this.dialogImageUrl = url;
            this.fileName = res.data.fileName;
            this.$emit("sendPhotoUrl", res.data.url);
          }
        });
        return false;
      }
      return isJPG && isLt2M;
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/styles/base.scss';

.upupload {
  img {
    width: 100%;
  }
}
</style>